<template>
  <Modal
    v-model="visible"
    :title="$t('page.customer.add_tag')"
    width="600"
    @on-cancel="handleCancel"
    footer-hide
  >
    <!-- 搜索框 + 排序按钮 -->
    <div style="display: flex; margin-bottom: 12px;">
      <Input
        v-model="search"
        placeholder="Search to find or create tags"
        clearable
        style="flex: 1; margin-right: 10px;"
      />
      <!-- <Button @click="sortTags">🔃 Alphabetical</Button> -->
    </div>

    <!-- 创建标签按钮 -->
    <div v-if="canCreateTag" style="margin-bottom: 10px;">
      <Button type="success" size="small" @click="createTag">
        {{$t('page.customer.create_tag')}}：“{{ search }}”
      </Button>
    </div>

    <!-- 多选标签 -->
    <CheckboxGroup v-model="selectedValues" class="tag-list">
      <Checkbox
        v-for="tag in filteredTags"
        :key="tag.value"
        :label="tag.value"
        style="display: block; margin: 5px 0;"
      >
        {{ tag.label }}
      </Checkbox>
    </CheckboxGroup>

    <!-- <p style="color: red; margin-top: 10px;">这个标签 可以自己编辑</p> -->

    <!-- Footer -->
    <div style="text-align: right; margin-top: 20px;">
      <Button @click="handleCancel" style="margin-right: 8px;">{{$t('page.product.cancel')}}</Button>
      <Button type="primary" @click="handleSave">{{$t('page.product.save')}}</Button>
    </div>
  </Modal>
</template>

<script>
// 假设你有这个接口
// const createTagApi = async (label) => {
//   // 模拟创建接口
//   return new Promise(resolve => {
//     setTimeout(() => {
//       resolve({
//         success: true,
//         data: {
//           label,
//           value: label.toLowerCase().replace(/\s+/g, '_')  // 模拟唯一 ID
//         }
//       });
//     }, 500);
//   });
// };
import { createTagsApi } from "@/api/storeCustomer";
export default {
  name: 'TagSelector',
  props: {
    value: Boolean,
    tags: {
      type: Array,
      default: () => []
    },
    selected: {
      type: Array, // [{label, value}]
      default: () => []
    }
  },
  data() {
    return {
      visible: this.value,
      search: '',
      localTags: [...this.tags],
      selectedValues: this.selected.map(t => t.value)
    };
  },
  watch: {
    value(val) {
      this.visible = val;
      if (val) {
        this.localTags = [...this.tags];
        this.selectedValues = this.selected.map(t => t.value);
      }
    },
    visible(val) {
      this.$emit('input', val);
    }
  },
  computed: {
    filteredTags() {
      if (!this.search) return this.localTags;
      return this.localTags.filter(tag =>
        tag.label.toLowerCase().includes(this.search.toLowerCase())
      );
    },
    canCreateTag() {
      const exists = this.localTags.some(
        tag => tag.label.toLowerCase() === this.search.trim().toLowerCase()
      );
      return this.search.trim() && !exists;
    }
  },
  methods: {
    sortTags() {
      this.localTags.sort((a, b) => a.label.localeCompare(b.label));
    },
    async createTag() {
      const label = this.search.trim();
      if (!label) return;

      try {
        const res = await createTagsApi({name:label},0);
        if (res.code == 0) {
          const newTag = res.data;
          this.localTags.push(newTag.info);
          this.selectedValues.push(newTag.info.value);
          this.search = '';
        } else {
          this.$Message.error('创建标签失败');
        }
      } catch (e) {
        this.$Message.error('请求错误');
      }
    },
    handleSave() {
      const selectedObjects = this.localTags.filter(tag =>
        this.selectedValues.includes(tag.value)
      );
      this.$emit('save', selectedObjects);
      this.visible = false;
    },
    handleCancel() {
      this.visible = false;
    }
  }
};
</script>

<style scoped>
.tag-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px 0;
}
</style>
